<?php
/*
+--------------------------------------------------------------------------
|   WeCenter [#RELEASE_VERSION#]
|   ========================================
|   by WeCenter Software
|   © 2011 - 2014 WeCenter. All Rights Reserved
|   http://www.wecenter.com
|   ========================================
|   Support: WeCenter@qq.com
|
+---------------------------------------------------------------------------
*/


if (!defined('IN_ANWSION')) {
    die;
}

class sms_class extends AWS_MODEL
{


    public function validCode($mobile,$code)
    {
        if (isset(AWS_APP::session()->mobile_code)) {
            if (AWS_APP::session()->mobile_code == $code){
                $result = $this->fetch_one('sms', 'id', "mobile = '" . $this->quote($mobile) . "' and code = '" . $this->quote($code) ."'");
                if(empty($result)){
                    return false;
                }
                return true;
            }else{
                return false;
            }

        } else {
            return false;
        }
    }

    public function validCodeNumber($mobile)
    {
        $now_time = time();
        $half_hour = strtotime('-30 minute');
        $number = $this->count('sms', 'create_time between ' . $half_hour . ' and ' . $now_time);
        if ($number >= 4)
            return false;
        else
            return true;
    }

    public function code()
    {
        if (AWS_APP::session()->mobile_code) {
            return AWS_APP::session()->mobile_code;
        } else {
            $code = mt_rand(1000, 9999);
            AWS_APP::session()->mobile_code = $code;
            AWS_APP::session()->setExpirationSeconds(60*2,'mobile_code');
            return $code;
        }
    }

    public function insert_sms($mobile, $code, $msg = '')
    {
        $sid = $this->insert('sms', [
            'mobile'      => $mobile,
            'code'        => $code,
            'msg'         => $msg,
            'create_time' => time(),
        ]);
        return $sid;
    }

    public function send($mobile)
    {
        $code = $this->code();
        $message = urlencode(mb_convert_encoding('【空指针】您的手机验证码是:' . $code, 'gbk', 'utf-8'));
        return AWS_APP::phone()->send($mobile, $code, $message);
    }
}
